package com.ry.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.ry.common.Constants;
import com.ry.model.dto.UserDTO;
import com.ry.model.entity.User;
import com.ry.model.vo.TokenVo;
import com.ry.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author ry
 * @since 2021-11-09 17:22
 **/
@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private StringRedisTemplate redisTemplate;
    
    @Override
    public String login(User user) {
        String token = RandomUtil.randomString(16);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        //key是token
        //value是User json格式字符串
        operations.set(Constants.TOKEN_KEY_PREFIX+token, JSONObject.toJSONString(user),2, TimeUnit.HOURS);

        //好像可以不使用签名进行验证
        //将sessionKey存到redis中,为了方便以后的拓展
        redisTemplate.opsForValue().set(Constants.SESSION_KEY_PREFIX+token,user.getSessionKey(),2,TimeUnit.HOURS);

        return token;
    }

    @Override
    public UserDTO getUserByToken(String token) {
        String userJson = redisTemplate.opsForValue().get(Constants.TOKEN_KEY_PREFIX + token);
        JSONObject jsonObject = JSONObject.parseObject(userJson);
        UserDTO userDTO = new UserDTO();
        userDTO.setId(jsonObject.getInteger("id"));
        userDTO.setNickname(jsonObject.getString("nickname"));
        userDTO.setAvatarUrl(jsonObject.getString("avatarUrl"));
        userDTO.setCoverUrl(jsonObject.getString("coverUrl"));
        userDTO.setMotto(jsonObject.getString("motto"));
        userDTO.setGender(jsonObject.getInteger("gender"));
        userDTO.setToken(token);

        return userDTO;
    }
}
